import { observable, action, toJS } from 'mobx';
import { ListAdvanced, RouteLayout, Form, ListPage } from 'weaver-mobile-page';
import { Toast, Tools } from 'weaver-mobile'; 

import * as API from '../api/esearch.js';
const getLabel = Tools.getLabel;
export default class eSearchStore {
  @observable showCheck = false;
  @observable listAd = new ListAdvanced.Store({route: '/esearch', id:'search'})
  @observable layout = new RouteLayout.Store({route: '/esearch',id:'list'});
  @observable layoutSearch = new RouteLayout.Store({route: '/esearch',id:'search'});
  @observable contentType = [];
  @observable perHot = [];
  @observable sysHot = [];
  @observable searchList = [];
  @observable urlMapping = [];
  @observable searchResult = '';
  @observable pageCount = 1;
  @observable pageindex = 1;
  @observable pagesize = 20;
  @observable loading = false;

  @observable btnShow = false;
  @observable isSearchStart = true; 
  @observable searchStatus = '';
  
  @observable skipSearchParams = {
    currentPage: 0,
    lastRealNumber: 0, 
  };

  @observable baseDatas = {};

  @observable initLoading = false;
  @observable activeKey = 0;
  @observable extraLayout = new RouteLayout.Store({route: '/esearch',id:'extraConditin'});
  @observable searchResultLayout = new RouteLayout.Store({route: '/esearch',id:'search'});
  @observable extraForm = new Form.Store({ route: '/esearch/extraConditin'});
  @observable addCommonSetForm = new Form.Store({ route: '/esearch/commonSet/add'});
  @observable commonSetLayout = new RouteLayout.Store({ route: '/esearch', id: 'commonSet' });
  @observable addCommonSetLayout = new RouteLayout.Store({ route: '/esearch/commonSet', id: 'add' });
  @observable commonSetListStore = new ListPage.Store();
  @observable tabParams = {};
  @observable searchInputVal = ''; 
  @observable page_uuid = ''; //FULLSEARCH
  @observable homeBaseDatas = {};
  @observable browserKeyArr = [];
  @observable search_type = ''; 
  @observable recordParams = {};
  @observable tagParams = {};
  @observable topbarVisible = true;
  // @observable page_descStr = '';
  @observable page_title = '';
  @observable urlParams = undefined;
  @observable urlSearchParams = {};

  @action
  setParams = (params={}, callback) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });

    typeof callback === 'function' && callback();
  }

  // 获取微搜基础信息
  getBaseData = (params, callback) => {
    params = {
      page_uuid: this.page_uuid,
      ...params
    };
    this.initLoading = true;
    API.getBaseData(params).then(res => {
      this.initLoading = false;
      if(res) {
        if(Array.isArray(res.contentType)) {
          if(res.contentType && res.contentType.length > 0) {
            if(this.urlSearchParams.type === undefined) {
              this.tabParams = res.contentType[0];
            }
          }
          res.contentType = res.contentType.map((res, index) => {
            return {
              ...res,
              title: res.name,
            }
          });
        }
        res.contentType && (this.contentType = res.contentType);
        if(res.hotKey) {
          this.perHot = res.hotKey.per;
          this.sysHot = res.hotKey.sys;
          this.urlMapping = res.urlMapping;
        }
        this.baseDatas = res;
        if(res.search_type) {
          this.search_type = res.search_type;
          if(res.search_type === 'ALL' && !(this.urlSearchParams.hideTitle === 'true')) {
            this.topbarVisible = true;
          } else {
            this.topbarVisible = false;
          }
        }
        if(res.page_uuid) {
          this.page_uuid = res.page_uuid;
        }
        if(res.page_title) {
          this.page_title = res.page_title;
          window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: res.page_title });
        }

        typeof callback === 'function' && callback();
      }
    });
  }
  // 按条件搜索
  doSearch = (param) => {
    let params = {...param,sourceType: 'MOBILE'};
    this.isSearchStart = false;
    this.loading = true;
    params = {
      ...params,
      otherJson: this.urlParams,
      ...this.skipSearchParams
    };
    this.skipSearchParams.currentPage = param.pageIndex;

    API.doSearch(params).then(res => { 
      this.loading = false;
      this.searchStatus = res.status;
      if(res && res.api_status) {

        this.skipSearchParams.lastRealNumber = res.lastRealNumber || -1;

        Array.isArray(res.list) && (this.searchList = this.searchList.concat(res.list));
        this.searchResult = res.result;
        this.pageCount = res.pagecount;
        this.pageindex = res.pageindex;
        this.isSearchStart = true;
      }
      if (res && res.status === '-1') {
        Toast.offline(getLabel('131448','查询超时，请联系管理员。') , 2);
      }
      if(res && res.contentType && (res.contentType !== '') ) {
        Array.isArray(toJS(this.contentType)) && this.contentType.forEach(v => {
          if(v.key === res.contentType) {
            this.tabParams = v;
          }
        });
      }
    });
  }
  // 微搜结果提交
  submitResult = (param) => {
    let params = {...param,sourceType: 'MOBILE'}
    API.submitResult(params).then(

    );
  }

  // 微搜结果提交
   showSubmit = (param) => {
    API.showSubmit(param).then(res => {
      this.btnShow = res.ret;
    });
  }

  // 高级搜索
  getAdvancedForm = (params, callback) => {
    params = {
      page_uuid: this.page_uuid,
      fromCondition: 1,
      search_type: this.tabParams.key,
      ...params,
    };
    this.extraForm = new Form.Store({ route: '/esearch/extraConditin'});
    API.getSearchTagDtl(params).then(res => {
      if(res.ret === 'success') {
        this.browserKeyArr = res.browserKeyArr;
        this.extraForm.initForm(res.fields, '/esearch/extraConditin');
        typeof callback === 'function' && callback();
      }
    });
  }

  clearExtraForm = () => { // 清空高级搜索数据
    this.extraForm.setState({ formData: {} });
  }


  // 添加常用条件设置
  getSearchTagDtl = (params, callback) => {
    params = {
      page_uuid: this.page_uuid,
      search_type: this.tabParams.key,
      ...params
    };
    API.getSearchTagDtl(params).then(res => {
      if(res.ret === 'success') {
        if(res.fields[0].items) {
          res.fields[0].items =  res.fields[0].items.map(res => {
            if(res.domkey[0] === "CREATERID_select") {
              res.selectLinkageDatas[2].browserConditionParam.viewAttr = 3;
            }
            if(res.domkey[0] === 'CREATEDATE_date_select') {
              res.viewAttr = 3;
            }
            return res;
          });
        }

        this.addCommonSetForm.initForm(res.fields, '/esearch/commonSet/add');
        this.browserKeyArr = res.browserKeyArr;
        typeof callback === 'function' && callback();
      }
    });
  }

  // 常用条件设置
  getCommonSetForms = (param, callback) => {
    API.getCommonSetForms(param).then(res => {
      let data = [0, 1, 2, 3, 4].map((theme, i) => ({
          img: '/avatar.jpg',
          imgstr: '<img style="width: 100px; height: 60px" src="/avatar.jpg"></img>',
          title: `标题_${theme}`,
          id: `id_00${i}`,
          user: `用户_${i}`,
          time: `2018-09-0${i}`,
      }));
      this.commonSetListStore.setState({data});
      typeof callback === 'function' && callback();
    });
  }

  filterAdParams = () => {
    let browserKeyArr = this.browserKeyArr;
    let extraForm = this.extraForm;
    const formParams = extraForm.formParams;
    let search_json = { ...formParams };
    
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);

    Object.keys(search_json).forEach(key => {
      let json = toJS(search_json[key]);
      if(typeof json === 'object') { // 过滤obj
        let objA = { ...search_json[key] };
        search_json = {
          ...search_json,
          ...objA
        };
      } 
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }

      browserKeyArr.forEach(v => {// 过滤浏览按钮span
        if(key.indexOf('span') > -1 && key.indexOf(v) > -1) {
          delete search_json[key];
        }
      });
 
      if(search_json[key] === '') {// 过滤''值
        delete search_json[key];
      }
    });
    if(search_json.CREATERID !== undefined && search_json.CREATERID !== '') {
      search_json = {
        ...search_json,
        CREATERID_select: '2'
      };
    }

    return search_json;
  }


  filterAdParams1 = (form, browserKeyArr) => {
    if(form === undefined || browserKeyArr === undefined) return;
    const formParams = form.formParams;
    let search_json = { ...formParams };
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);

    Object.keys(search_json).forEach(key => {
      let json = toJS(search_json[key]);
      if(typeof json === 'object') { // 过滤obj
        let objA = { ...search_json[key] };
        search_json = {
          ...search_json,
          ...objA
        };
      } 
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }
      browserKeyArr.forEach(v => {// 过滤浏览按钮span
        if(key.indexOf('span') > -1 && key.indexOf(v) > -1) {
          delete search_json[key];
        }
        
      });
 
      if(search_json[key] === '') {// 过滤''值
        delete search_json[key];
      }
    });
    let idsSet = new Set();

    Array.isArray(browserKeyArr) && browserKeyArr.forEach(key => {
      let browserArr = toJS(search_json[key]);
      if(browserArr && typeof browserArr[0] === 'object' && Array.isArray(browserArr)) {
        browserArr.forEach(f => {
          f.id && idsSet.add(f.id);
        });
        search_json = {
          ...search_json,
          [key]: Array.from(idsSet)
        };
      }
    })
    if(search_json.CREATERID !== undefined && search_json.CREATERID !== '') {
      if(search_json.CREATERID.length > 0) {
        search_json = {
          ...search_json,
          CREATERID_select: '2'
        };
      }
    }

    return search_json;
  }

  // 点击tag
  onSearchClick = (type, dataParams, history, search) => {
    // const { doSearch, setParams } = this.props.esearchStore;
    // const { contentType, pagesize, pageIndex} = dataParams;
    // const { layoutSearch } = this.props.esearchStore;
    /** 
     * keyword: 关键字,searchType: 全文检索/标题检索,contentType:模块名,pageIndex: 当前页,
     * pageSize: 每页条数,noAuth:无权限模块,voice:是否语音
     * lastkey: 语音二次查询条件,otherjson: 其他搜索条件*/ 
    let params = {
      keyword: this.searchInputVal,
      contentType: this.tabParams.key || 'ALL',
      pageIndex: this.pageindex,
      pageSize: 20,
      otherjson: '',
      searchType: 'CONTENT',
      page_uuid: this.page_uuid,
      page_search_json: JSON.stringify(this.filterAdParams()),
      ...dataParams
    }
    if(params.keyword !== '') {
      // 去除前后空格
      params.keyword = params.keyword.trim();
    }
    if(dataParams.keyword && (dataParams.keyword !== this.searchInputVal)) {
      this.searchInputVal = dataParams.keyword;
    }
    // let params = {keyword: key,contentType: contentType,otherjson: '',searchType: 'CONTENT',pageIndex: pageIndex,pageSize: 20}
    if (type === 'enter') { // 切换搜索类型时,重启从头开始展示
      // this.refs.seaList.k = 0; 
      params = {...params, pageIndex: 1}
      // this.setState({pIndex: 1});
      this.setParams({searchList: []});
      this.resetSkipSearchParams();
    }
    this.setParams({loading: true});
    if(params.keyword !== '') {
      this.doSearch(params);
      this.doSaveHistorySearch({ searchkey: params.keyword });
      history && history.push(`${this.searchResultLayout.path}${search}`);
    }else{
      if(history.location && history.location.pathname === "/esearch") {
        // 首页不搜索
      } else {
        this.clearExtraForm();
        this.tagParams = {};
        history && history.push(`/esearch${search}`);
      }
    }
  }

  resetSkipSearchParams = () => { // 重置跳转参数
    this.setParams({
      skipSearchParams: {
        currentPage: 0,
        lastRealNumber: 0,
      }
    });
  }

  getCustompageBaseDatas = (params, callback) => {
    // cuspage_type: 1:基础信息  2: 仅获取历史搜索记录 （刷新的时候） 3: 仅获取常用条件（刷新的时候）  其他值: 全部获取
    params = {
      page_uuid: this.page_uuid,
      ...params
    };
    this.homeLoading = true;
    API.getCustompageBaseDatas(params).then(result => {
      this.homeLoading = false;
      if(result.api_status) {
        if(result.cuspage_type === '1') {
          this.homeBaseDatas = result;
        }
        if(result.historySearchList) {
          this.homeBaseDatas.historySearchList = result.historySearchList;
          this.baseDatas.historySearchList = result.historySearchList;
        }
        if(result.tagList) {
          this.homeBaseDatas.tagList = result.tagList;
          this.baseDatas.tagList = result.tagList;
        }
        if(result.page_showHistory !== undefined) {
          this.homeBaseDatas.page_showHistory = result.page_showHistory;
        }
        if(result.page_showCommonConditions !== undefined) {
          this.homeBaseDatas.page_showCommonConditions = result.page_showCommonConditions;
        }
        typeof callback === 'function' && callback(result);
      }
    });
  }

  //删除历史搜索条件
  delHistorySearch = (params, callback) => { 
    params = {
      page_uuid: this.page_uuid,
      ...params
    };
    API.delHistorySearch(params).then(result => {
      if(result.api_status) {
        typeof callback === 'function' && callback();
      }
    });
  }

  //删除常用条件
  delSearchTag = (params, callback) => { 
    params = {
      page_uuid: this.page_uuid,
      ...params
    };
    API.delSearchTag(params).then(result => {
      if(result.api_status) {
        typeof callback === 'function' && callback();
      }
    });
  }

  showAndHideSearchTag = (params, callback) => { 
    params = {
      page_uuid: this.page_uuid,
      ...params
    };
    API.showAndHideSearchTag(params).then(result => {
      if(result.api_status) {
        typeof callback === 'function' && callback();
      }
    });
  }

  doSaveSearchTag = (params, callback) => { 
    params = {
      page_uuid: this.page_uuid,
      search_type: this.tabParams.key,
      enable: 1,
      ...params
    };
    API.doSaveSearchTag(params).then(result => {
      if(result.api_status) {
        typeof callback === 'function' && callback();
      }
    });
  }

  // 高级搜索
  getAdConditions = (params, callback) => {
    params = {
      page_uuid: this.page_uuid,
      fromCondition: 1,
      search_type: this.search_type,
      ...params,
    };
    API.getSearchTagDtl(params).then(result => {
      if(result.api_status) {
        this.adSearchForm.initFormFields(result.fields);
        this.adSearchFormConditions = result.fields;
        typeof callback === 'function' && callback();
      }
    });
  }

  doSaveHistorySearch = (params, callback) => { 
    params = {
      page_uuid: this.page_uuid,
      search_type: this.search_type,
      ...params
    };
    API.doSaveHistorySearch(params).then(result => {
      if(result.api_status) {
        this.getCustompageBaseDatas({ cuspage_type: '2' });
        typeof callback === 'function' && callback();
      }
    });
  }
  


}